package mspbots.autotask.data.core.appointments;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Log4j2
@Component
@RequiredArgsConstructor
public class AppointmentReceiver {

    private final AppointmentRepository appointmentRepository;

//    @RabbitListener(queues = "auto-task.appointments.sync")
    public void syncTask(ResultMsg content) {
        Appointment appointment = Appointment.builder().otherId(content.getId())
                .tenantId(content.getTenantId()).syncTime(content.getSyncDate())
                .createdTime(LocalDateTime.parse(content.getEntity().get("createDateTime").textValue(),
                        DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .updatedTime(LocalDateTime.parse(content.getEntity().get("updateDateTime").textValue(),
                        DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .entity(content.getEntity())
                .build();

        if (ObjectUtils.isEmpty(appointment.getOtherId())){
            return;
        }
        this.appointmentRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(ticket -> {
                    appointment.setId(ticket.getId());
                    return appointment;

                })
                .defaultIfEmpty(appointment)
                .flatMap(this.appointmentRepository::save)
                .block(Duration.ofSeconds(10));
    }
}
